import { defineStore } from 'pinia';
import { ref, onMounted } from 'vue';
import request from '@/utils/request';
import { showNotification } from '@/utils/notify';
import type { ConfirmCourseParams, ConfirmCourseRes, Course, CoursePage, CourseSchedule, GetAllCourseSchedulesRes, GetCoursesByTokenRes, SelectCourseResponse, TeacherCourse } from '@/types/course';



export const useCourseStore = defineStore('course', () => {
    const courses = ref<Course[]>([]);
    const total = ref(0); // 总课程数量
    const currentPage = ref(1); // 当前页码
    const pageSize = ref(10); // 每页显示的课程数量
    const selectedCourses = ref<CourseSchedule[]>([]); 
    const teacherCourses = ref<TeacherCourse[]>([]); // 教师课程列表
    const teacherSelectedCourses = ref<string[]>([]); // 教师已选课程列表
    const courseSchedules = ref<CourseSchedule[]>([])
    const fetchCourses = async () => {
        try {
            const { data } = await request.get<CoursePage>(
                `/api/courses/page?current=${currentPage.value}&size=${pageSize.value}`
            );

            courses.value = data.records;
            total.value = data.total;
        } catch (error) {
            showNotification("获取课程列表失败", true);
        }
    };

    const addCourse = async (course: Course) => {
        const { code } = await request.post<{ code: number; data: object }>('/api/courses/add', course);
        if (code === 200) {
            showNotification("课程添加成功", false);
            fetchCourses()

        } else {
            showNotification("课程添加失败", true);
        }
    };

    const updateCourse = async (index: number, updatedCourse: Course) => {
        try {
            const courseId = updatedCourse.courseId;
            const { code, data } = await request.post<{ code: number; data: object }>(
                `/api/courses/update/${courseId}`,
                updatedCourse
            );
            if (code === 200) {
                showNotification("课程更新成功", false);
                fetchCourses()
            } else {
                showNotification("课程更新失败", true);
            }
        } catch (error) {
            showNotification("课程更新失败", true);
        }
    };

    const deleteCourse = async (index: number) => {
        try {
            const courseId = courses.value[index].courseId;
            const { code, data } = await request.post<{ code: number; data: object }>(
                `/api/courses/remove/${courseId}`
            );
            if (code === 200) {
                courses.value.splice(index, 1);
                showNotification("课程删除成功", false);
            } else {
                showNotification("课程删除失败", true);
            }
        } catch (error) {
            showNotification("课程删除失败", true);
        }
    };

    const fetchSelectedCourses = async () => {
        const {code,data,message} = await request.get<{code:number,message:string,data:CourseSchedule[]}>('/api/course-schedules/get-selected')
        if(code===200){
            selectedCourses.value = data
        }else{
            showNotification(message,true)
        }
    }
    //开设课程
    const addCourseSchedule = async (course:ConfirmCourseParams) => {
        await request.post<ConfirmCourseRes>('/api/course-schedules/open', course)
        fetchCourseSchedules()
    }
    //确认课程
    const confirmCourseSchedule  = async (course:ConfirmCourseParams) => {
        
        await request.post<ConfirmCourseRes>('/api/course-schedules/confirm', course)
    }
    //删除课程
    const removeCourseSchedule = async (courseScheduleId:string) => {
        await request.get<ConfirmCourseRes>(`/api/course-schedules/remove/${courseScheduleId}`)
        fetchCourseSchedules()
    }

    const fetchCourseSchedules = async () => {
       const {data}=await request.get<GetAllCourseSchedulesRes>('/api/course-schedules/get-all') 
       courseSchedules.value =data 
    }

    //根据获取教师的课程
    const fetchTeacherCourses = async () => {
        try {
            const { data } = await request.get<GetCoursesByTokenRes>(`/api/course-schedules/teacher`);
            teacherCourses.value = data
        } catch (error) {
            showNotification("获取教师课程列表失败", true);
        }
    };
    const changePage = (page: number) => {
        currentPage.value = page;
        fetchCourses();
    };

    // 学生选课
    const selectCourse = async (courseScheduleId: number) => {
        try {
            const { code, message } = await request.get<SelectCourseResponse>(`/api/course-schedules/select-course/${courseScheduleId}`);
            if (code === 200) {
                showNotification("选课成功", false);
              
            } else {
                showNotification(message, true);
            }
        } catch (error) {
            showNotification("选课失败", true);
        }
    };

    // 学生取消选课
    const cancelSelectCourse = async (courseScheduleId: number) => {
            const { code, message } = await request.get<{code:number,message:string}>(`/api/course-schedules/cancel?courseScheduleId=${courseScheduleId}`);
            if (code === 200) {               
                 showNotification("取消选课成功", false);               
               
            } else {
                showNotification(message, true);
            }
    };

 

    onMounted(() => {
        fetchCourses();
    });

    return {
        courses,
        total,
        currentPage,
        pageSize,
        teacherCourses,
        courseSchedules,
        selectedCourses,
        fetchSelectedCourses,
        addCourse,
        updateCourse,
        deleteCourse,
        fetchCourses,
        changePage,
        selectCourse,
        cancelSelectCourse,
        fetchTeacherCourses,
        addCourseSchedule,
        fetchCourseSchedules,
        confirmCourseSchedule,
        removeCourseSchedule
    };
});